/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.avradiation.web;

import cz.muni.fi.pb138.avradiation.DB.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;

/**
 *
 * @author huzvak
 */
public class LocationManagerImpl implements LocationManager {
    
    private static final Logger logger = Logger.getLogger(
         LocationManagerImpl.class.getName());
    
    private DataSource ds;

    /** 
     * Set DataSource to acces to DB
     * @param DataSource ds  
     * @throws IllegalArgumentException     
     */
    public void setDataSource(DataSource ds) {
        if(ds == null) {
            logger.log(Level.SEVERE,"DataSource is null");
            throw new IllegalArgumentException("DataSource is null");
        }
        this.ds = ds;
    }
    
    /** 
     * Check if DataSource is not null
     * @param DataSource ds  
     * @throws IllegalStateException     
     */
    private void checkDataSource() {
        if (ds == null) {
            logger.log(Level.SEVERE,"DataSource is null");
            throw new IllegalStateException("DataSource is null");
        }
    }

    @Override
    public Location findLocationById(Long id) {
        if (id == null) {
            logger.log(Level.SEVERE,"Parameter [id] is null");
            throw new IllegalArgumentException("Parameter [id] is null");
        }
        
        if (ds == null) {
            logger.log(Level.SEVERE,"DataSource is null");
            throw new IllegalStateException("DataSource is null.");
        }

        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = ds.getConnection();
            st = conn.prepareStatement(
                    "SELECT idlocation, name FROM location WHERE id = ?");
            st.setLong(1, id);

            ResultSet rs = st.executeQuery();

            if (rs.next()) {
                Location result = new Location();

                result.setId(rs.getLong("idlocation"));
                result.setName(rs.getString("name"));                
                assert !rs.next();
                logger.log(Level.INFO,"Location found", result);
                return result;
            } else {
                return null;
            }

        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error when getting location from DB", ex);
            throw new RuntimeException("Error when getting location from DB", ex);
        } finally {
            DBUtils.closeConnection(conn);
        }
    }

    @Override
    public Collection<Location> getAllLocations() {
        
        if (ds == null) {
            logger.log(Level.SEVERE,"DataSource is null");
            throw new IllegalStateException("DataSource is null.");
        }

        Connection conn = null;
        PreparedStatement st = null;
        try {
            conn = ds.getConnection();
            st = conn.prepareStatement("SELECT idlocation, name FROM location ORDER BY name");
            ResultSet rs = st.executeQuery();
            Collection<Location> locations = new LinkedList<Location>();
            while (rs.next()) {
                Location result = new Location();
                result.setId(rs.getLong("idlocation"));
                result.setName(rs.getString("name"));
                
                System.err.println("NAME: " + result.getName());
                
                locations.add(result);
            }
            logger.log(Level.INFO,"Locations succesfully selected");
            return Collections.unmodifiableCollection(locations);
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error when getting all locations from DB", ex);
            throw new RuntimeException("Error when getting all locations from DB", ex);
        } finally {
            DBUtils.closeConnection(conn);
        }
    }
    
}
